/*
 * FileName：AuthInterceptor.java
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.smart.primary.interceptor;

import com.smart.common.Constants;
import com.smart.common.util.PropertiesUtil;
import com.smart.common.util.SessionUtil;
import com.smart.common.util.WxMemoryCacheClient;
import com.smart.sys.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户拦截器
 *
 * @author hermit
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    public String[] allowUrls;// 也可以注解

    public void setAllowUrls(String[] allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
        if (null != allowUrls && allowUrls.length >= 1) {
            for (String url : allowUrls) {
                if (requestUrl.equals(url)) {
                    return true;
                }
            }
        }
        // 微信请求不予拦截 20180722
        String sessionid = request.getSession().getId();
        String openId = WxMemoryCacheClient.getOpenid(sessionid);
        if (openId != null && !openId.equals("")) {
            return true;
        }

        SysUser user = SessionUtil.getUser();
        if (null == user) {
            if (isAjaxRequest(request)) {
                // 赋值错误状态码
                response.setStatus(300);
                // 前端弹出登录框
                response.setHeader("sessionState", "notLogin");
            } else {
                logger.info("未登录url:{}", requestUrl);
                // 跳转到登录页
                response.sendRedirect("/views/login.html");
            }
            return false;
        } else {
            SessionUtil.session.setMaxInactiveInterval(60 * 60 * 30);
            //判断用户的角色是否是演示模式
            if (PropertiesUtil.getBoolean("demoMode") && Constants.TEMP_USER_TYPE.equals(user.getUserType())) {
                if (requestUrl.contains("save") || requestUrl.contains("update") || requestUrl.contains("delete") || requestUrl.contains("deleteBatch")) {
                    // 赋值错误状态码
                    response.setStatus(303);
                    // 前端弹出登录框
                    response.setHeader("userType", "temp");
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        boolean isAjax = request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
        return isAjax;
    }

//	public static boolean isReferer(HttpServletRequest request) {
//		return Util.isEmpty(request.getHeader("Referer")) && request.getMethod().equals("GET");
//	}
}
